import React, { Component } from 'react'
import { Input, Button, message } from 'antd'
import { withRouter } from 'react-router-dom'
import { requestLogin } from '../../api/user'
import './Login.scss'
import { LockOutlined, UserOutlined } from '@ant-design/icons'

class Login extends Component {

    state = {
        username: '',
        password: ''
    }

    componentDidMount () {

    }

    checkOut (params) {
        let { history } = this.props
        requestLogin(params).then(res => {
            if (res.code === '200' || res.code === 200) {
                sessionStorage.setItem('token', res.data.token)
                sessionStorage.setItem('type', res.data.type)
                sessionStorage.setItem('author', JSON.stringify(res.data.author))
                sessionStorage.setItem('current', this.state.username)

                if (!res.data.freeze) {
                    message.success('登录成功')
                    setTimeout(() => {
                        history.replace('/home/statistic')
                    }, 1500)
                } else {
                    message.error('账号已被冻结')
                }

            } else if (res.code === '10003' || res.code === '400' || res.code === 400) {
                message.error('密码错误')
            } else {
                message.error('用户不存在')
            }
        })
    }

    onLogin () {
        let { username, password } = this.state
        if (!username.length) {
            message.error('用户名不为空')
            return
        }
        if (!password.length) {
            message.error('密码不为空')
            return
        }
        this.checkOut({
            adminname: username,
            password: password
        })
    }

    onInput (e) {
        let { name, value } = e.target
        this.setState({
            [name]: value,
        })
    }

    render () {
        return (
            <div className="container">
                <div className="loginFrame">
                    <h1>Sportwear Admin</h1>
                    <Input name="username" size="large" autoComplete="off" placeholder="username"
                           value={this.state.username}
                           onInput={this.onInput.bind(this)} prefix={<UserOutlined/>}/>
                    <div style={{ height: 22 }}></div>
                    <Input.Password name="password" size="large" placeholder="password" value={this.state.password}
                                    onInput={this.onInput.bind(this)} prefix={<LockOutlined/>}/>
                    <Button onClick={this.onLogin.bind(this)} block type="primary"
                            style={{ margin: 10, marginTop: 25 }}>登录</Button>
                </div>
            </div>
        )
    }
}

export default withRouter(Login)
